var jsonApi = "";

init();

function init() {
    // 清空下拉框选项
    var interfaceSelect = document.getElementById('interface');
    if(interfaceSelect)
    {
        while (interfaceSelect.firstChild) {
            interfaceSelect.removeChild(interfaceSelect.firstChild);
        }
    }


    var url = "../json/api.json";
    var request = new XMLHttpRequest();
    request.open("get", url);
    request.send(null);
    request.onload = function () {
        if (request.status === 200) {
            jsonApi = JSON.parse(request.responseText);
            
            // 填充 API 数据到下拉框
            jsonApi.forEach(function(item) {
                var option = document.createElement('option');
                option.value = item.url;
                option.textContent = item.name;
                    if(interfaceSelect)
                    {
                        interfaceSelect.appendChild(option);
                    }
            });

            console.log("=============== 初始化配置文件完成 ====================");
        }

        // 从存储加载自定义配置
        chrome.storage.sync.get(['api_data'], function(result) {
            if (typeof result.api_data !== "undefined") {
                var arr = JSON.parse(result.api_data);
                arr.forEach(function(item) {
                    var option = document.createElement('option');
                    option.value = item.url;
                    option.textContent = item.name;
                    interfaceSelect.appendChild(option);
                });
                console.log("=============== 初始化内存配置完成 ====================");
            }
        });

        // 设置默认选项
        chrome.storage.sync.get(['default_api', 'default_open'], function(result) {
            var radioInputs = document.querySelectorAll('.input_td input[type="radio"]');

            // 设置默认接口
            if (typeof result.default_api !== "undefined") {
                interfaceSelect.value = result.default_api.url;
            } else {
                chrome.storage.sync.set({ "default_api": jsonApi[0] });
                interfaceSelect.value = jsonApi[0].url;
            }

            // 设置默认开关状态
            if (typeof result.default_open !== "undefined") {
                var targetValue = result.default_open.toString();
                Array.prototype.forEach.call(radioInputs, function(radio) {
                    if (radio.value === targetValue) {
                        radio.checked = true;
                    }
                });
            } else {
                radioInputs[0].checked = true;
            }

            console.log("=============== 获取默认配置完成 ====================");
        });
    };
}